from flask import Flask, request, jsonify
import pandas as pd
import smtplib
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import json

app = Flask(__name__)

# 邮件配置（建议从环境变量或配置文件中读取）
MAIL_CONFIG = {
    'smtp_server': 'smtp.163.com',
    'smtp_port': 25,
    'sender': 'XXX@163.com',
    'password': 'XXX'  # 使用授权码而非密码
}

def send_dataframe_by_email(df, receiver, subject="数据报告"):
    """
    发送DataFrame数据到指定邮箱
    :param df: pandas DataFrame
    :param receiver: 收件人邮箱
    :param subject: 邮件主题
    :return: (success, message)
    """
    if df.empty:
        return False, "数据为空，不发送邮件"
    
    try:
        # 创建邮件对象
        msg = MIMEMultipart('alternative')
        msg['From'] = Header(f"Data Service System", 'utf-8')
        msg['To'] = Header(receiver, 'utf-8')
        msg['Subject'] = Header(subject, 'utf-8')
        
        # HTML内容
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>{subject}</title>
            <style>
                body {{ font-family: Arial, sans-serif; margin: 20px; }}
                h1 {{ color: #0066cc; }}
                table {{ border-collapse: collapse; width: 100%; }}
                th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
                th {{ background-color: #f2f2f2; }}
            </style>
        </head>
        <body>
            <h1>{subject}</h1>
            <p>以下是自动生成的数据报告，请查收：</p>
            {df.to_html(index=False)}
            <p><small>此邮件由数据服务系统自动发送，请勿直接回复</small></p>
        </body>
        </html>
        """
        max_date = datetime.now().date()
        # 添加HTML内容
        msg.attach(MIMEText(html_content, 'html', 'utf-8'))
        
        # 添加CSV附件
        csv_attachment = MIMEText(df.to_csv(index=False), 'base64', 'utf-8')
        csv_attachment["Content-Type"] = 'text/csv'
        csv_attachment["Content-Disposition"] = f'attachment; filename="data_report_{max_date}.csv"'
        msg.attach(csv_attachment)
        
        # 发送邮件
        with smtplib.SMTP(MAIL_CONFIG['smtp_server'], MAIL_CONFIG['smtp_port']) as server:
            server.starttls()
            server.login(MAIL_CONFIG['sender'], MAIL_CONFIG['password'])
            server.sendmail(MAIL_CONFIG['sender'], receiver, msg.as_string())
        
        return True, "邮件发送成功"
    
    except Exception as e:
        return False, f"邮件发送失败: {str(e)}"


@app.route('/api/send_multi_data', methods=['POST'])
def send_multi_data():
    data = request.json
    stocks_data = data['data']
    receiver = data['receiver']
    subject = data['subject']
    selected_date = stocks_data['selected_date']  # 获取日期
    
    try:
        # 创建邮件
        msg = MIMEMultipart()
        msg['From'] = '同花顺数据中心@ths.com'
        msg['To'] = receiver
        msg['Subject'] = subject
        
        # 生成HTML内容（包含创业板、一字板和2板以上数据）
        html_content = f"""
        <h1>zt报告（{selected_date}）</h1>
        
        <h2>创业板涨停股票</h2>
        {pd.DataFrame(stocks_data['创业板股票']).to_html()}
        
        <h2>一字板涨停股票</h2>
        {pd.DataFrame(stocks_data['一字板股票']).to_html()}
        
        <h2>2板及以上股票</h2>
        {pd.DataFrame(stocks_data['两板及以上股票']).to_html()}
        """
        
        # 添加HTML内容
        msg.attach(MIMEText(html_content, 'html', 'utf-8'))
        
        # 添加CSV附件（可选：可以分别导出创业板、一字板和2板以上的数据）
        combined_df = pd.concat([
            pd.DataFrame(stocks_data['创业板股票']).assign(类型='创业板'),
            pd.DataFrame(stocks_data['一字板股票']).assign(类型='一字板'),
            pd.DataFrame(stocks_data['两板及以上股票']).assign(类型='2板及以上')
        ])
        
        csv_attachment = MIMEText(combined_df.to_csv(index=False), 'base64', 'utf-8')
        csv_attachment["Content-Type"] = 'text/csv'
        csv_attachment["Content-Disposition"] = f'attachment; filename="stock_report_{selected_date}.csv"'
        msg.attach(csv_attachment)
        
        # 发送邮件
        with smtplib.SMTP(MAIL_CONFIG['smtp_server'], MAIL_CONFIG['smtp_port']) as server:
            server.starttls()
            server.login(MAIL_CONFIG['sender'], MAIL_CONFIG['password'])
            server.sendmail(MAIL_CONFIG['sender'], receiver, msg.as_string())

        return jsonify({'message': '邮件发送成功！'}), 200
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/send_data', methods=['POST'])
def send_data():
    """API接口：接收JSON格式的DataFrame数据并发送邮件"""
    try:
        # 获取请求数据
        data = request.json
        if not data:
            return jsonify({"success": False, "message": "未提供有效数据"}), 400
        
        # 解析参数
        df_data = data.get('data', [])  # DataFrame数据
        receiver = data.get('receiver')  # 收件人邮箱
        subject = data.get('subject', '数据报告')  # 邮件主题
        
        if not receiver:
            return jsonify({"success": False, "message": "收件人邮箱不能为空"}), 400
        
        # 将数据转换为DataFrame
        df = pd.DataFrame(df_data)
        
        # 发送邮件
        success, message = send_dataframe_by_email(df, receiver, subject)
        
        if success:
            return jsonify({"success": True, "message": message})
        else:
            return jsonify({"success": False, "message": message}), 500
    
    except Exception as e:
        return jsonify({"success": False, "message": f"服务器错误: {str(e)}"}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)